﻿using Orleans;
using Pay.Admin.App_Start;
using Pay.Cache;
using Pay.Core;
using Pay.Model;
using Pay.Model.Dto;
using Pay.Model.Model;
using Pay.Service;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Pay.Admin.Controllers
{
    public class CommonController : Controller
    {
        // GET: Common
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 上传支付宝二维码 并且解析生成新的二维码保存到数据库
        /// </summary>
        /// <returns></returns>
        public JsonResult Upload()
        {
            try
            {
                var files = Request.Files[0];
                var id = Convert.ToInt64(Request["id"].ToString());
                if (files != null)
                {

                    decimal amount = 0;
                    string description = string.Empty;
                    var FullName = files.FileName.Substring(0, files.FileName.LastIndexOf("."));
                    if (FullName.Contains("#"))
                    {
                        var arry = FullName.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                        amount = Convert.ToDecimal(arry[0]);
                        description = arry.Length > 1 ? arry[1] : "";
                    }
                    else
                    {
                        amount = Convert.ToDecimal(FullName);
                    }
                    string ext = System.IO.Path.GetExtension(files.FileName);
                    string newfileName = Guid.NewGuid().ToString().Substring(0, 8) + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
                    string originalPath = "/upload/alipayImage/" + DateTime.Now.ToString("yyyyHHdd");
                    string path = Request.MapPath(originalPath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var finnal2 = Path.Combine(originalPath, newfileName);
                    var finnal = Path.Combine(path, newfileName);
                    files.SaveAs(Path.Combine(path, newfileName));

                    //解析二维码
                    Bitmap bit = new Bitmap(finnal);
                    string qrUrl = QrCodeHelper.QRCodeDecoderUtil(bit);

                    //生成新的二维码
                    var img = QrCodeHelper.QRCodeEncoderUtil(qrUrl);
                    var tempUrl = "/upload/payImage/" + DateTime.Now.ToString("yyyyHHdd");
                    string newFolder = Request.MapPath("/upload/payImage/" + DateTime.Now.ToString("yyyyHHdd"));
                    if (!Directory.Exists(newFolder))
                    {
                        Directory.CreateDirectory(newFolder);
                    }
                    string fileName = Guid.NewGuid().ToString().Substring(0, 8) + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                    string newAddress = Path.Combine(newFolder, fileName);
                    string newAddress2 = Path.Combine(tempUrl, fileName);
                    img.Save(newAddress);

                    //存入数据库
                    var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>("0");


                    QRCodeInfo model = new QRCodeInfo()
                    {

                        Address = finnal2,
                        AliAccountId = id,
                        CreateTime = DateTime.Now,
                        QRcodeUrl = qrUrl,
                        NewAddress = newAddress2,
                        NewImageName = fileName,
                        Amount = amount,
                        Description = description
                    };
                    service.Add(model);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Json(new { });
        }
        /// <summary>
        /// 接受阿里支付宝订单记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowCrossSiteJson]
        public async Task<ActionResult> AcceptAliInfo(List<AliOrderInput> Orders)
        {
            if (Orders != null && Orders.Any())
            {

                //存入redis
                var nameSpace = "payService:" + Orders[0].SystemAccount;
                RedisHelper helper = new RedisHelper();
                var list = helper.ListRange<AliOrderInput>(nameSpace);
                if (list == null)
                {
                    for (int i = 0; i < Orders.Count; i++)
                    {
                        helper.ListLeftPush<AliOrderInput>(nameSpace, Orders[i]);
                    }

                }
                else
                {
                    var allData = helper.ListRange<AliOrderInput>(nameSpace);
                    //获取list长度

                    foreach (var item in Orders)
                    {
                        var temp = allData.Where(c => c.OrderNo == item.OrderNo);
                        if (temp == null)
                        {
                            var length = helper.ListLength(nameSpace);
                            if (length >= 100)
                            {
                                helper.ListRightPop<AliOrderInput>(nameSpace);
                            }

                            helper.ListLeftPush<AliOrderInput>(nameSpace, item);

                            //插入数据库
                            var service = GrainClient.GrainFactory.GetGrain<IAliOrderService>(item.SystemAccount);
                            var info = new AliOrderInfo()
                            {
                                AliOrderNo = item.OrderNo,
                                Amount = item.Amount,
                                CreateTime =Convert.ToDateTime( item.CreateTime),
                                SysTime = DateTime.Now,
                                Des = item.Des,
                                Status = item.Status
                            };
                           await service.Add(info);
                        }
                    }
                }

                return Json(new { success=true,msg="传入成功" });
            }
            else
            {
                return Json(new { success = false, msg = "传入数据为空" });
            }
        }
    }
}